package cn.iocoder.yudao.module.cmt.service.service;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import cn.iocoder.yudao.module.cmt.controller.admin.service.vo.*;
import cn.iocoder.yudao.module.cmt.dal.dataobject.service.ServiceRequestDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.cmt.dal.mysql.service.ServiceRequestMapper;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.cmt.enums.ErrorCodeConstants.*;

@Service
@Validated
public class ServiceRequestServiceImpl implements ServiceRequestService {

    @Resource
    private ServiceRequestMapper serviceRequestMapper;

    @Override
    public Long createServiceRequest(ServiceRequestSaveReqVO createReqVO) {
        ServiceRequestDO serviceRequest = BeanUtils.toBean(createReqVO, ServiceRequestDO.class);
        serviceRequestMapper.insert(serviceRequest);
        return serviceRequest.getId();
    }

    @Override
    public void updateServiceRequest(ServiceRequestSaveReqVO updateReqVO) {
        validateServiceRequestExists(updateReqVO.getId());
        ServiceRequestDO updateObj = BeanUtils.toBean(updateReqVO, ServiceRequestDO.class);
        serviceRequestMapper.updateById(updateObj);
    }

    @Override
    public void deleteServiceRequest(Long id) {
        validateServiceRequestExists(id);
        serviceRequestMapper.deleteById(id);
    }

    private void validateServiceRequestExists(Long id) {
        if (serviceRequestMapper.selectById(id) == null) {
            throw exception(SERVICE_REQUEST_NOT_EXISTS);
        }
    }

    @Override
    public ServiceRequestDO getServiceRequest(Long id) {
        return serviceRequestMapper.selectById(id);
    }

    @Override
    public PageResult<ServiceRequestDO> getServiceRequestPage(ServiceRequestPageReqVO pageReqVO) {
        return serviceRequestMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteServiceRequestListByIds(List<Long> ids) {
        ids.forEach(this::validateServiceRequestExists);
        serviceRequestMapper.deleteBatchIds(ids);
    }

}
